import { Request, Response, NextFunction } from 'express'
import { checkUserInfo } from '@server/auth/check-auth'
import { UnauthorizedError } from '@server/error/errors'
import { AuthInfo } from '@data/auth-info'

// 创建权限断言对象
function createAuthAssert(authInfo: AuthInfo): Express.AuthAssert {
  return {
    canViewAbout: () => {
      if (!authInfo.canViewAbout) {
        throw new UnauthorizedError('You are not authorized to view the about page')
      }
    },
    canManageTodos: () => {
      if (!authInfo.canManageTodos) {
        throw new UnauthorizedError('You are not authorized to manage todos')
      }
    },
    canManageGroups: () => {
      if (!authInfo.canManageGroups) {
        throw new UnauthorizedError('You are not authorized to manage groups')
      }
    },
    canManageTags: () => {
      if (!authInfo.canManageTags) {
        throw new UnauthorizedError('You are not authorized to manage tags')
      }
    },
  }
}

// 鉴权中间件
export function authMiddleware(req: Request, res: Response, next: NextFunction) {
  try {
    const userInfo = checkUserInfo(req)
    req.auth = {
      ...userInfo,
      assert: createAuthAssert(userInfo.auth),
    }
    next()
  } catch (error) {
    next(error)
  }
}
